package sort;

/**
 * 冒泡排序
 * @author Tang Jiujia
 * @since 13:30 2020-04-10
 */
public class BubbleSort {

    /**
     * 冒泡排序
     *
     * @param a	要排序的数据
     * @return
     */
    public static void bubbleSort(int[] a) {
        int n = a.length;
        if (n <= 1) {
            return;
        }
        for (int i = 0; i < n; i++) {
            //本次冒泡是否进行了元素的位置交换，用于排序优化
            boolean sorted = false;
            for (int j = 0; j < n - i - 1; j++) {
                if (a[j] > a[j+1]) {
                    int tmp = a[j];
                    a[j] = a[j+1];
                    a[j+1] = tmp;
                    //本次冒泡有排序
                    sorted = true;
                }
            }
            //进行了交换，提前退出
            if (!sorted) {break;}
        }
    }



    public static void main(String[] args) {
        int[] a = {5, 9, 8, 2, 1, 9, 6, 3, 2};
        bubbleSort(a);
        for (int value : a) {
            System.out.print(value + " ");
        }
    }
}
































